package com.kewu.controller;

import com.kewu.bean.Fileup;
import com.kewu.dao.FileUploadMapper;
import com.kewu.utils.MybatisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@ResponseBody
@Slf4j
public class FileUploadAndDownloadController {
    SqlSession session = MybatisUtils.getSession(true);
    FileUploadMapper mapper = session.getMapper(FileUploadMapper.class);

    @PostMapping("/upload")
    public String FileUpload(@RequestParam("upload") MultipartFile multipartFile,
                             @RequestParam("md5") String md5,
                              @RequestParam("size") int size
                            ) throws IOException {
        System.out.println("/upload");
        Fileup fileup = mapper.findByMd5(md5);
        if (fileup!= null) {
            return md5;
        }

        if (!multipartFile.isEmpty()) {
            //保存到文件服务器，OSS服务器
            String originalFilename = multipartFile.getOriginalFilename();
            File file = new File("");
            String filePath = file.getCanonicalPath();
            filePath = filePath + "\\src\\main\\resources\\File\\" + originalFilename;
            multipartFile.transferTo(new File(filePath));
            fileup=new Fileup();
            fileup.setMd5(md5);
            fileup.setFilePath(filePath);
            fileup.setSize(size);

            int insertMd5 = mapper.insertMd5(fileup);
            if (insertMd5>0)
                return md5;
        }
        return "上传失败";
    }

    @GetMapping("/upload")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, String md5) throws IOException {
        Fileup fileup = mapper.findByMd5(md5);

        if (fileup.getFilePath() != null ) {
            File scFileDir = new File(fileup.getFilePath());
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(scFileDir.getName(), "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(scFileDir);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("下载成功！");
            } catch (Exception e) {
                System.out.println("下载失败！");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            return "文件不存在";
        }
        return "";
    }

    /*上传前MD5校验*/
    @GetMapping("/md5Check")
    public Map md5Check(String md5){
        log.info("/md5Check");
        Map<String, Boolean> map2 = new HashMap<>();
        Fileup fileup = mapper.findByMd5(md5);
        if (fileup!=null && fileup.getMd5().length()>0)
        {
            log.info("文件已存在,秒传成功");
            map2.put("msg",true);
            return map2;
        }
        map2.put("msg",false);
        return map2;
    }
}

